package cn.com.haopy.yue.ai.wx.annotation.support;

import cn.com.haopy.yue.ai.core.component.CacheComponent;
import cn.com.haopy.yue.ai.core.utils.RedisCachePreFix;
import cn.com.haopy.yue.ai.db.entity.arisk.HOSUser;
import cn.com.haopy.yue.ai.wx.annotation.LoginUser;
import cn.com.haopy.yue.ai.wx.constant.Constant;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

@Configuration
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    public static final String LOGIN_TOKEN_KEY = Constant.WX_LOGIN_TOKEN_KEY;

    private CacheComponent cacheComponent;

    public LoginUserHandlerMethodArgumentResolver(CacheComponent cacheComponent) {
        this.cacheComponent = cacheComponent;
    }


    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(Integer.class) && parameter.hasParameterAnnotation(LoginUser.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {


        String token = request.getHeader(LOGIN_TOKEN_KEY);
        if (token == null || token.isEmpty()) {
            return null;
        }

        // return UserTokenManager.getUserId(token);


        HOSUser user = cacheComponent.getObj(RedisCachePreFix.USERINFO.getCachePreFix() + token, HOSUser.class);
        if (user == null) {
            return null;
        } else {
            String localToken = cacheComponent.getRaw(RedisCachePreFix.USERTOKEN.getCachePreFix() + user.getId());
            if (null == localToken || localToken.isEmpty() || !token.equals(localToken)) {
                return null;
            }
        }
        return user.getId();

    }
}
